//
//  PPHTTPRequest.m
//  PPNetworkHelper
//
//  Created by AndyPang on 2017/4/10.
//  Copyright © 2017年 AndyPang. All rights reserved.
//

#import "PPHTTPRequest.h"
//#import "SJInterfaceConst.h"


@implementation PPHTTPRequest
+ (NSURLSessionTask *)postWithURL:(NSString *)URL  parameters:(id)parameters loadStr:(NSString *)loadStr isLoad:(BOOL)isLoad sucess:(PPRequestSuccess)success failure:(PPRequestFailure)failure {
    NSString *url = [NSString stringWithFormat:@"%@%@", kApiPrefix,URL];
    
    return [self requestWithURL:url isPost:YES parameters:parameters loadStr:loadStr isLoad:isLoad success:success failure:failure];
}
+ (NSURLSessionTask *)getWithURL:(NSString *)URL parameters:(id)parameters
                         loadStr:(NSString *)loadStr isLoad:(BOOL)isLoad
                          sucess:(PPRequestSuccess)success failure:(PPRequestFailure)failure {
    NSString *url = [NSString stringWithFormat:@"%@%@", kApiPrefix,URL];
    
    return [self requestWithURL:url isPost:NO parameters:parameters loadStr:loadStr isLoad:isLoad success:success failure:failure];
}


+ (NSURLSessionTask *)uploadFileWithURL:(NSString *)URL params:(id)params name:(NSString *)name filePath:(NSString *)filePath success:(PPRequestSuccess)success failure:(PPRequestFailure)failure {
    NSString *url = [NSString stringWithFormat:@"%@%@", kApiPrefix,URL];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    return [manager POST:url parameters:params headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSError *error = nil;        
        [formData appendPartWithFileURL:[NSURL URLWithString:filePath] name:name error:&error];
        (failure && error) ? failure(error) : nil;
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];

}

+ (NSURLSessionTask *)uploadFilesWithURL:(NSString *)URL params:(id)params files:(NSArray *)files progress:(PPRequestProgress)uploadProgress success:(PPRequestSuccess)success failure:(PPRequestFailure)failure {
    NSString *url = [NSString stringWithFormat:@"%@%@", kApiPrefix,URL];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    return [manager POST:url parameters:params headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (ASFileConfig *file in files) {
            [formData appendPartWithFileData:file.fileData name:file.name fileName:file.fileName mimeType:file.fileType];
        }
    } progress:^(NSProgress * _Nonnull upload) {
        uploadProgress(upload.fractionCompleted*100);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}

+ (NSURLSessionTask *)uploadImageWithURL:(NSString *)URL params:(id)params name:(NSString *)name images:(NSArray *)images fileNames:(NSArray<NSString *> *)fileNames imageScale:(CGFloat)imageScale imageType:(NSString *)imageType success:(PPRequestSuccess)success failure:(PPRequestFailure)failure {
    NSString *url = [NSString stringWithFormat:@"%@%@", kApiPrefix,URL];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    return  [manager POST:url parameters:params headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (NSUInteger i = 0; i < images.count; i++) {
            // 图片经过等比压缩后得到的二进制文件
            NSData *imageData = UIImageJPEGRepresentation(images[i], imageScale ?: 1.f);
            // 默认图片的文件名, 若fileNames为nil就使用
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *imageFileName = [NSString stringWithFormat:@"%@%ld.%@",str,i,imageType?:@"jpg"];
            
            [formData appendPartWithFileData:imageData
                                        name:name
                                    fileName:fileNames ? [NSString stringWithFormat:@"%@.%@",fileNames[i],imageType?:@"jpg"] : imageFileName
                                    mimeType:[NSString stringWithFormat:@"image/%@",imageType ?: @"jpg"]];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];

}
/*
 配置好PPNetworkHelper各项请求参数,封装成一个公共方法,给以上方法调用,
 相比在项目中单个分散的使用PPNetworkHelper/其他网络框架请求,可大大降低耦合度,方便维护
 在项目的后期, 你可以在公共请求方法内任意更换其他的网络请求工具,切换成本小
 */

#pragma mark - 请求的公共方法
//无缓存
+ (NSURLSessionTask *)requestWithURL:(NSString *)URL isPost:(BOOL)isPost parameters:(NSDictionary *)parameter loadStr:(NSString *)loadStr isLoad:(BOOL)isLoad success:(PPRequestSuccess)success failure:(PPRequestFailure)failure
{
    // 在请求之前你可以统一配置你请求的相关参数 ,设置请求头, 请求参数的格式, 返回数据的格式....这样你就不需要每次请求都要设置一遍相关参数
    // 设置请求头
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    if(isLoad){
        [QMUITips showLoading:loadStr inView:KeyWindow];
    }
    
    // 发起请求
    if (isPost) {
        return [manager POST:URL parameters:parameter headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [QMUITips hideAllTipsInView:KeyWindow];
            // 在这里你可以根据项目自定义其他一些重复操作,比如加载页面时候的等待效果, 提醒弹窗....
            success(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [QMUITips hideAllTipsInView:KeyWindow];
            // 同上
            failure(error);
        }];
        
    } else {
        return  [manager GET:URL parameters:parameter headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [QMUITips hideAllTipsInView:KeyWindow];
            
            success(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [QMUITips hideAllTipsInView:KeyWindow];
            
            failure(error);
        }];
    }
}
@end
